const {
  GiftShopModel
} = require('../../../utils/giftshop-model.js');
var giftShopModel = new GiftShopModel();
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: null,
    phoneShow: false,
    encryptedDataUser: '',
    ivUser: '',
    memberAddressId: '',
    cartDetail: null, //购物车列表
    cartExpiredDetail: [], //失效商品列表
    cartTotalPrice: [], //购物车总价
    checkedAll: false, //是否勾选 false 未勾选  true已勾选
    disabled: true, //下单的点击按钮
    numDisabled: false, //是否能编辑商品
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {

  },

  /**
   * 购物车列表
   */
  getCartList: function () {
    const shopInfo = wx.getStorageSync('shopInfo')
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: shopInfo.shopId, //门店id
      memberAddressId: this.data.memberAddressId
    }
    giftShopModel.cartList(param).then(data => {
      this.setData({
        cartDetail: data.cartDetail || [],
        cartExpiredDetail: data.cartExpiredDetail || [],
        cartTotalPrice: data.cartTotal.totalPrice ? data.cartTotal.totalPrice : []
      })
      this.allCheckedState(data.cartDetail); //全选状态
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 全选状态
   * checked 0 未勾选  1已勾选
   */
  allCheckedState(cartDetail) {
    if (cartDetail.length > 0) {
      let checkedGoods = cartDetail.filter(item => item.checked == 0) || [] //未勾选的商品
      let noCheckedGoods = cartDetail.filter(item => item.checked == 1) || [] //已勾选的商品
      this.setData({
        checkedAll: checkedGoods.length > 0 ? false : true, //控制全选按钮
        disabled: noCheckedGoods.length > 0 ? false : true //控制下单按钮
      })
    }
  },

  /**
   * 购物车全选
   */
  checkAllGoods: function () {
    wx.reportAnalytics('cart_check_all');
    this.setData({
      checkedAll: !this.data.checkedAll
    }, () => {
      this.setCartCheck()
    })
  },

  /**
   * 勾选购物车单个商品
   */
  checkSingleGoods: function (e) {
    wx.reportAnalytics('cart_select_single');
    let that = this;
    if (!that.data.numDisabled) {
      that.setData({
        numDisabled: true
      }, function () {
        let detail = e.currentTarget.dataset.detail //当前索引
        let checked = detail.checked == 1 ? 0 : 1
        that.setCartEdit(detail.cartDetailId, detail.quantity, detail.selectedPriceType, checked)
      })
    }
  },

  /**
   * 减商品数量
   */
  decrease: function (e) {
    wx.reportAnalytics('cart_quantity_decrease');
    let that = this;
    if (!that.data.numDisabled) {
      that.setData({
        numDisabled: true
      }, function () {
        let detail = e.currentTarget.dataset.detail //当前索引
        let quantity = parseInt(detail.quantity); //单个商品数量
        if (quantity > 1) {
          that.setCartEdit(detail.cartDetailId, quantity - 1, detail.selectedPriceType, detail.checked)
        } else {
          that.setData({
            numDisabled: false
          })
        }
      })
    }
  },

  /**
   * 加商品数量
   */
  increase: function (e) {
    wx.reportAnalytics('cart_quantity_increase');
    let detail = e.currentTarget.dataset.detail //当前索引
    if (detail.quantity < 99) {
      let that = this;
      if (!that.data.numDisabled) {
        that.setData({
          numDisabled: true
        }, function () {
          let quantity = parseInt(detail.quantity) + 1; //单个商品数量
          that.setCartEdit(detail.cartDetailId, quantity, detail.selectedPriceType, detail.checked)
        })
      }
    } else {
      wx.showToast({
        title: `购买上限99`,
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 输入框编辑商品数量
   */
  editNum: function (e) {
    let that = this;
    let detail = e.currentTarget.dataset.detail //当前索引
    if (e.detail.value > 99 || e.detail.value == '' || e.detail.value == 0) {
      if (e.detail.value > 99) {
        wx.showToast({
          title: `购买上限99`,
          icon: 'none',
          duration: 2000
        })
      }
      setTimeout(function () {
        that.setCartEdit(detail.cartDetailId, parseInt(detail.quantity), detail.selectedPriceType, detail.checked)
      }, 1500)
    } else {
      let quantity = parseInt(e.detail.value); //单个商品数量
      that.setCartEdit(detail.cartDetailId, quantity, detail.selectedPriceType, detail.checked)
    }
  },

  /**
   * 编辑购物车
   * @param {*购物车明细ID} cartDetailId 
   * @param {*数量} quantity 
   * @param {*选中的支付方式0金额、1积分、2彩票} selectedPriceType 
   * @param {*是否勾选0 未勾选  1已勾选} checked 
   */
  setCartEdit: function (cartDetailId, quantity, selectedPriceType, checked) {
    let that = this;
    const shopInfo = wx.getStorageSync('shopInfo')
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: shopInfo.shopId, //门店id
      cartDetailId: cartDetailId, //购物车明细ID
      quantity: quantity, //数量
      selectedPriceType: selectedPriceType, //选中的支付方式0金额、1积分、2彩票
      checked: checked, //是否勾选0 未勾选  1已勾选
    }
    giftShopModel.cartEdit(param).then(data => {
      that.setData({
        numDisabled: false,
        cartDetail: data.cartDetail || [],
        cartExpiredDetail: data.cartExpiredDetail || [],
        cartTotalPrice: data.cartTotal.totalPrice ? data.cartTotal.totalPrice : []
      }, () => {
        that.allCheckedState(data.cartDetail); //全选状态
      })
    }).catch(err => {
      that.setData({
        numDisabled: false
      })
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 勾选购物车全部商品
   */
  setCartCheck: function () {
    let that = this;
    const shopInfo = wx.getStorageSync('shopInfo')
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: shopInfo.shopId, //门店id
      cartDetailIdList: [], //购物车明细ID(传空为全选)
      checked: that.data.checkedAll ? 1 : 0, //是否勾选0 未勾选  1已勾选
    }
    giftShopModel.cartCheck(param).then(data => {
      that.setData({
        cartDetail: data.cartDetail || [],
        cartExpiredDetail: data.cartExpiredDetail || [],
        cartTotalPrice: data.cartTotal.totalPrice ? data.cartTotal.totalPrice : []
      }, () => {
        that.allCheckedState(data.cartDetail); //全选状态
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 清空失效商品
   */
  setCartClear: function () {
    let that = this
    let cartDetailIdList = []
    that.data.cartExpiredDetail.forEach(item => {
      cartDetailIdList.push(item.cartDetailId)
    })
    wx.showModal({
      title: '确定清空失效商品？',
      cancelColor: '#333333', //取消文字的颜色
      confirmColor: '#333333', //确定文字的颜色
      success(res) {
        if (res.confirm) {
          wx.reportAnalytics('cart_expired_goods_clear');
          const shopInfo = wx.getStorageSync('shopInfo')
          var param = {
            merchantId: wx.getStorageSync('merchantId'), //商户ID
            shopId: shopInfo.shopId, //门店id
            cartDetailIdList: cartDetailIdList, //购物车明细ID(传空为全选)
          }
          giftShopModel.cartClear(param).then(data => {
            that.setData({
              cartDetail: data.cartDetail || [],
              cartExpiredDetail: data.cartExpiredDetail || [],
              cartTotalPrice: data.cartTotal.totalPrice ? data.cartTotal.totalPrice : []
            })
          }).catch(err => {
            wx.showToast({
              title: `${err.error}`,
              icon: 'none',
              duration: 2000
            })
          })
        }
      }
    })
  },

  /**
   * 删除商品
   */
  delCartGoods: function (e) {
    wx.reportAnalytics('cart_goods_delete');
    let cartDetailIdList = []
    cartDetailIdList.push(e.currentTarget.dataset.id)
    const shopInfo = wx.getStorageSync('shopInfo')
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: shopInfo.shopId, //门店id
      cartDetailIdList: cartDetailIdList, //购物车明细ID(传空为全选)
    }
    giftShopModel.cartDelete(param).then(data => {
      this.setData({
        cartDetail: data.cartDetail || [],
        cartExpiredDetail: data.cartExpiredDetail || [],
        cartTotalPrice: data.cartTotal.totalPrice ? data.cartTotal.totalPrice : []
      })
    }).catch(err => {
      wx.showToast({
        title: `$e{err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 去结算
   */
  settlement: function () {
    wx.reportAnalytics('cart_balance');
    let cartDetailIdList = []
    this.data.cartDetail.forEach(item => {
      if (item.checked == 1) {
        cartDetailIdList.push(item.cartDetailId)
      }
    })
    if (cartDetailIdList.length > 0) {
      const shopInfo = wx.getStorageSync('shopInfo')
      let that = this;
      that.setData({
        disabled: true
      }, () => {
        var param = {
          merchantId: wx.getStorageSync('merchantId'), //商户ID
          shopId: shopInfo.shopId, //门店id
          addressId: '', //地址ID
        }
        param.balanceCartDetailList = cartDetailIdList //购物车明细id
        giftShopModel.balanceInfo(param).then(data => {
          wx.navigateTo({
            url: `/pages/giftShop/fillOrder/index?currency=${JSON.stringify(cartDetailIdList)}&paymentType=1&from=shoppingcart`
          })
          that.setData({
            disabled: false,
          })
        }).catch(err => {
          this.setData({
            disabled: false,
          })
          wx.showToast({
            title: `${err.error}`,
            icon: 'none',
            duration: 2000
          })
        })
      })
    } else {
      wx.showToast({
        title: `您还没有选择商品哦`,
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 正常商品手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.cartDetail.forEach(function (v, i) {
      if (v.isTouchMove) { //只操作为true的
        v.isTouchMove = false;
      }
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartDetail: this.data.cartDetail || []
    })
  },

  /**
   * 正常商品滑动事件处理,一次只能滑出一个删除按钮
   */
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化X坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化Y坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.cartDetail.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) {
        return;
      }
      if (i == index) {
        if (touchMoveX > startX) { //右滑
          v.isTouchMove = false
        } else { //左滑
          v.isTouchMove = true
        }
      }
    })
    that.setData({
      cartDetail: that.data.cartDetail || []
    })
  },

  /**
   * 失效商品手指触摸动作开始 记录起点X坐标
   */
  touchstartExpired: function (e) {
    //开始触摸时 重置所有删除
    this.data.cartExpiredDetail.forEach(function (v, i) {
      if (v.isTouchMoveExpired) { //只操作为true的
        v.isTouchMoveExpired = false;
      }
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartExpiredDetail: this.data.cartExpiredDetail || []
    })
    console.log(this.data.cartExpiredDetail)
  },

  /**
   * 失效商品滑动事件处理,一次只能滑出一个删除按钮
   */
  touchmoveExpired: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化X坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化Y坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.cartExpiredDetail.forEach(function (v, i) {
      v.isTouchMoveExpired = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) {
        return;
      }
      if (i == index) {
        if (touchMoveX > startX) { //右滑
          v.isTouchMoveExpired = false
        } else { //左滑
          v.isTouchMoveExpired = true
        }
      }
    })
    that.setData({
      cartExpiredDetail: that.data.cartExpiredDetail || []
    })
  },

  /**
   * 计算滑动角度
   * start 起点坐标
   * end 终点坐标　　* Math.PI 表示一个圆的周长与直径的比例，约为 3.14159;PI就是圆周率π，PI是弧度制的π,也就是180°   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  getUserInfo({
    detail
  }) {
    const {
      encryptedData,
      iv
    } = detail
    if (encryptedData) {
      this.setData({
        encryptedDataUser: encryptedData,
        ivUser: iv,
        phoneShow: true
      })
    }
  },
  getOrderInfo() {
    if (this.data.formId) {
      memberModel.userMessage({
        formIds: [this.data.formId]
      })
    }
    this.getCartList();
    this.setData({
      isLogin: true
    })
  },

  formSubmit1(e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isLogin: app.globalData.isLogin
    })
    if (app.globalData.isLogin) {
      this.getCartList();
    }
  },

  /**
   * 商品详情
   */
  goDetail(e) {
    const skuId = e.currentTarget.dataset.sku
    const item = e.currentTarget.dataset.item
    const shopInfo = wx.getStorageSync('shopInfo')
    wx.reportAnalytics('goods_detail', {
      shop_id: shopInfo.shopId,
      sku_id: skuId,
    });
    wx.navigateTo({
      url: `/pages/giftShop/goodsDetail/index?shopId=${shopInfo.shopId}&skuId=${skuId}&channelGoodsId=${item.channelGoodsId}`
    })
  },
})